package dang.action.cart;

import dang.action.DangAction;
import dang.common.Constant;
import dang.common.CookieUtil;
import dang.dao.DaoFactory;
import dang.dao.ProductDao;
import dang.entity.Product;

public class AddItemAction extends DangAction{
	private int id;
	private boolean added;

	public String execute() {
		String cartInfoId=(String) session.get("cartInfoId").toString();
		ProductDao dao = DaoFactory.getProductDao(Constant.TYPE_BOOK);
		try {
			Product product=dao.findById(id);
			CartItem item=new CartItem();
			item.setProduct(product);
			
			Cart cart = (Cart) session.get("cart");
			if(cart==null){
				cart=new Cart();
				String cartInfo=CookieUtil.getCookie("cartInfo"+cartInfoId,request);
				cart.load(cartInfo);
				session.put("cart", cart);
			}
			
			boolean itemAdded=cart.add(item);
			if(itemAdded){
				item.setQty(1);
				CookieUtil.saveCookie("cartInfo"+cartInfoId, cart.store(), response);
				added=true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public boolean isAdded() {
		return added;
	}

	public void setAdded(boolean added) {
		this.added = added;
	}
}
